package uds.android.fitdroid.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

public class DataHelperBLOB {
	private static final String DATABASE_NAME = "data.db";
	private static final int DATABASE_VERSION = 1;
	private static final String TABLE_NAME = "data";

	private Context context;
	private SQLiteDatabase db;

	private SQLiteStatement insertStmt;
	//private SQLiteStatement updateStmt;
	private static final String INSERT = "insert into " + TABLE_NAME + "(id, data) values (?, ?)";
	//private static final String UPDATE = "update " + TABLE_NAME + " set data = ? where id = ?" ;
	   
	public DataHelperBLOB(Context context) {
	   this.context = context;
	   OpenHelper openHelper = new OpenHelper(this.context);
	   this.db = openHelper.getWritableDatabase();
	   this.insertStmt = this.db.compileStatement(INSERT);
	   //this.updateStmt = this.db.compileStatement(UPDATE);
	}
	  
	public SQLiteDatabase getDb() {
	   return this.db;
	}
	
	public long insertBLOB(String id, String data){
		this.insertStmt.bindLong(1, Long.parseLong(id));
		this.insertStmt.bindBlob(2, data.getBytes());
		return this.insertStmt.executeInsert();
	}
	
	//CAN RETURN NULL!!
	public byte[] getData(Long id){
		byte[] data = null;
		Cursor cursor = this.db.query(TABLE_NAME, new String [] {"data"}, "id="+id.toString(), null, null, null, null);
		if (cursor.moveToFirst()) {
	         do {
	        	data = cursor.getBlob(0);
	        	break; //only one should be there
	         } while (cursor.moveToNext());
	      }
	      if (cursor != null && !cursor.isClosed()) {
	         cursor.close();
	      }
	      return data;
	}
	
	private static class OpenHelper extends SQLiteOpenHelper {

	      OpenHelper(Context context) {
	         super(context, DATABASE_NAME, null, DATABASE_VERSION);
	      }

	      @Override
	      public void onCreate(SQLiteDatabase db) {
	         db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, data BLOB)");
	      }

	      @Override
	      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	         Log.w("Example", "Upgrading database, this will drop tables and recreate.");
	         db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
	         onCreate(db);
	      }
	   }
}
